package com.suvel.study.filter;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class RegisterIPFilter implements GlobalFilter, Ordered {

    private static final Map<String, List<Date>> ipMap = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        RequestPath path = request.getPath();
        System.out.println(path);
        if(path.toString().startsWith("/user/register")){
            String host = Objects.requireNonNull(request.getRemoteAddress()).getHostString();
            Date now = new Date();
            if (ipMap.get(host) == null){
                List<Date> list = new ArrayList<>();
                list.add(now);
                ipMap.put(host, list);
            }else {
                ipMap.get(host).add(now);
            }
            Date oneMinBefore = DateUtils.addMinutes(now, -1);
            List<Date> dates = ipMap.get(host);
            dates.removeIf(date -> date.compareTo(oneMinBefore) < 0);
            ipMap.put(host,dates);

            int count = ipMap.get(host).size();
            if (count>2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                String data = "count 2 more,try again after.";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }else {
                return chain.filter(exchange);
            }
        }else {
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
